<?php defined('SYSPATH') or die('No direct script access.');
require_once(APPPATH. 'classes/helpers/url.php');
require_once(APPPATH. 'classes/model/Model_UserProfile.php');
require_once(APPPATH. 'classes/model/Model_UserLogin.php');
require_once(APPPATH. 'classes/model/Model_UserComments.php');

class Controller_Register extends Controller {
	public function action_index() {
		if(!$this->request->is_ajax()) {
			throw new Kohana_HTTP_Exception_500();
		}
		$captcha = Arr::get($_POST, 'captcha', '');
		if(!Captcha::valid($captcha)) {
			echo "Invalid captcha";
			exit();
		}
		$fname = Arr::get($_POST, 'fname', '');
		$lname = Arr::get($_POST, 'lname', '');
		$email1 = Arr::get($_POST, 'email', '');
		$u1pwd1 = Arr::get($_POST, 'pwd1', '');
		$u1pwd2 = Arr::get($_POST, 'pwd2', '');
		$dob1 = Arr::get($_POST, 'dob', '');
		$sex = Arr::get($_POST, 'sex', '');
		if($sex == '0') $sex = Model_UserProfile::FEMALE;
		else if($sex == '1') $sex = Model_UserProfile::MALE;
		else {
			echo "Invalid sex";
			exit();
		}
		$date_arr = explode('-', $dob1);
		if(count($date_arr) != 3) {
			echo "Invalid date of birth";
			exit();
		}
		if(!checkdate($date_arr[1], $date_arr[0], $date_arr[2])) {
			echo "Invalid date of birth";
			exit();
		}
		$dob = $date_arr[2]."-".$date_arr[1]."-".$date_arr[0];
		$status1 = null;
		$um = new Model_UserLogin();
		$up = new Model_UserProfile();
		$uc = new Model_UserComments();
		$reg_status = '';
		if($fname != '' && $lname!='' && $email1!='' && $u1pwd1!=''	&& $dob1!='' && $u1pwd1==$u1pwd2)
		{
			try {
				$status1 = $um->createLogin($email1, $u1pwd1, Model_UserLogin::NETWORK_SELF, Model_UserLogin::ST_CREATED);
				$reg_status = "Registered success<br>";
			} catch(Exception $e) {
				$status1 = false;
				$reg_status = "Email already registered";
			}
			if($status1) {
				$up->setUserProfileData($status1, array('f_name'=>$fname,'l_name'=>$lname, 
									'sex' => Model_UserProfile::FEMALE, 'about_me'=>'',
									'wall_id' => 0, 'dob' => $dob));
				$this->sendConfirmationMail($status1, "$fname $lname", $email1, $u1pwd1);
			}
		} else {
			$reg_status = "Info left blank<br>";
		}
		echo $reg_status;
	}
	private function sendConfirmationMail($uid, $name, $email, $password) {
		$data = $uid.'``'.$name.'``'.$email.'``'.$password;
		$encoded = Encrypt::instance()->encode($data);
		$link = My_URL::app_url('register/confirmEmail/'.$encoded);
		$message = "Please <a href='$link' target=_blank>click here</a> to confirm your email.";
		$headers  = 'MIME-Version: 1.0' . "\r\n".
					'Content-type: text/html; charset=iso-8859-1' . "\r\n".
					'From: Couple Book <confirmation@couple-book.com>' . "\r\n" .
    				"To: $name <$email>" . "\r\n";
		if(Kohana::$environment === Kohana::PRODUCTION) {
			mail($email, 'Welcome to couple book', $message, $headers, '-fconfirmation@couple-book.com');
			echo "Go to your mailbox to activate your account. If you didnt see it, check in spams too.";
		} else {
			echo $message;
		}
	}
	public function action_confirmEmail($data) {
		$data = My_URL::removeFakeExt($data);
		$decoded = Encrypt::instance()->decode($data);
		$arr = explode('``', $decoded);
		if(count($arr) != 4) {
			echo "something went wrong";
			exit();
		}
		list($uid, $name, $email, $password) = $arr;
		$ul = new Model_UserLogin();
		$uid_db = $ul->getPendingUid($email, $password);
		if($uid != $uid_db) {
			echo "Invalid link email=$email passwd=$password uid=$uid, uid_db=$uid_db";
			exit();
		}
		$ul->setStatus($uid, Model_UserLogin::ST_ACTIVATED);
		echo "Activate successfully. Go to login <a href='".My_URL::app_url('')."'.>click here</a>";
	}
	public function action_forgot() {
		$email = Arr::get($_POST, 'email', '');
		$ul = new Model_UserLogin();
		$status = -1;
		$uid = $ul->getUidByEmail($email, Model_UserLogin::NETWORK_SELF, $status);
		if($status == Model_UserLogin::ST_BANNED) {
			echo "You are banned. contact admint.";
		} else if($status == Model_UserLogin::ST_CREATED) {
			echo "Your account not activated. Go to your email to activate.";
		} else if($status == Model_UserLogin::ST_ACTIVATED) {
			$data = $uid.'``'.$email.'``'.time();
			$encoded = Encrypt::instance()->encode($data);
			$link = My_URL::app_url('register/resetpswd/'.$encoded);
			$name = '';
			$message = "Please <a href='$link' target=_blank>click here</a> to reset. This link will expire in 1 hour.";
			$headers  = 'MIME-Version: 1.0' . "\r\n".
					'Content-type: text/html; charset=iso-8859-1' . "\r\n".
					'From: Couple Book <confirmation@couple-book.com>' . "\r\n" .
    				"To: $name <$email>" . "\r\n";
			if(Kohana::$environment === Kohana::PRODUCTION) {
				mail($email, 'Welcome to couple book', $message, $headers, '-fconfirmation@couple-book.com');
				echo "Go to your mailbox to reset password. If you didnt see it, check in spams too.";
			} else {
				echo $message;
			}
		} else {
			echo "Unknown internal error. contact admin.";
		}
	}
	public function action_resetpswd($data) {
		$data = My_URL::removeFakeExt($data);
		$decoded = Encrypt::instance()->decode($data);
		$arr = explode('``', $decoded);
		if(count($arr) != 3) {
			echo "something went wrong";
			exit();
		}
		list($uid, $email, $time) = $arr;
		if(time() - $time > 7200) {
			echo "Link expired";
			exit();
		}
		$pswd1 = Arr::get($_POST, 'password1', '');
		$pswd2 = Arr::get($_POST, 'password2', '');
		if($pswd1 == '' && $pswd2 == '') {
			echo <<<DOM
			<html><head><title>Reset Password</title></head><body>
			<form method="post">
			New Password: <input type='password' name='password1'><br>
			Password Repeat:<input type='password' name='password2'><br>
			<input type='submit' name='reset password'>
			</form>
			</body></html>
DOM;
		} else if($pswd1 != $pswd2) {
			echo <<<DOM
			<html><head><title>Reset Password</title></head><body>
			Password do not match. Try again.
			<form method="post">
			New Password: <input type='password' name='password1'><br>
			Password Repeat:<input type='password' name='password2'><br>
			<input type='submit' name='reset password'>
			</form>
			</body></html>
DOM;
		} else if($pswd1 == $pswd2) {
			$ul = new Model_UserLogin();
			$ul->setPassword($uid, $pswd1);
			echo "Password set successfully";
		} else {
			echo "something went wrong";
		}
	}
	public function __call($method, $args) {
		throw new Kohana_HTTP_Exception_500();
	}
}
